﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using WebUtils;

namespace OAuth.ServiceProviders
{
    public sealed class Yammer : DefaultOAuthServiceProvider
    {
        private const string REQUEST_URL = "https://www.yammer.com/oauth/request_token";
        private const string ACCESS_URL = "https://www.yammer.com/oauth/access_token";
        private const string USER_AUTH_URL = "https://www.yammer.com/oauth/authorize";

        readonly private Func<string, string> completeUrlUserAuthHandler;
        private string userAuthResponseCode;

        public Yammer(Func<string, string> pCompleteUrlUserAuthHandler) : base(
            new DefaultWebRequest(
                WebMethodVerbEnum.POST,
                REQUEST_URL,
                defaultEmptyParams,
                defaultEmptyParams,
                defaultParams),
            null) // we will override this method ourselves
        {
            completeUrlUserAuthHandler = pCompleteUrlUserAuthHandler;
        }

#if PocketPC

        public override SignatureMethod AccessTokenSignatureMethod
        {
            get { return SignatureMethods.Plaintext.Instance; }
        }

        public override SignatureMethod RequestTokenSignatureMethod
        {
            get { return SignatureMethods.Plaintext.Instance; }
        }

        public override SignatureMethod ProtectedResourceSignatureMethod
        {
            get { return SignatureMethods.Plaintext.Instance; }
        }

#endif

        public override IWebRequest AccessTokenRequest
        {
            get
            {
                return new DefaultWebRequest(
                    WebMethodVerbEnum.POST,
                    ACCESS_URL,
                    new UnEncodedURLParameter[] { new UnEncodedURLParameter() { Key = "callback_token", Value = userAuthResponseCode } },
                    defaultEmptyParams,
                    defaultParams);
            }
        }

        public override void WithRequestTokenResult(
            string pRequestToken, 
            string pRequestTokenSecret, 
            IEnumerable<UnEncodedURLParameter> pAdditionalParameters)
        {
            var completeUrl = string.Format(
                "{0}?oauth_token={1}", 
                USER_AUTH_URL, 
                pRequestToken);
            userAuthResponseCode = completeUrlUserAuthHandler(completeUrl);
        }
    }
}
